<template>
  <div class="count-down">
    <!-- 小时 -->
    <span class="block hour">{{ times.h }}</span>
    <!-- 冒号 -->
    <span class="colon">:</span>
    <!-- 分钟 -->
    <span class="block minute">{{ times.m }}</span>
    <!-- 冒号 -->
    <span class="colon">:</span>
    <!-- 秒钟 -->
    <span class="block second">{{ times.s }}</span>
  </div>
</template>

<script>
export default {
  data () {
    return {
      timer: 0,
      lastTime: 0,
      times: { h: '00', m: '00', s: '00' }
    }
  },

  props: {
    // 距离结束的时间戳
    endTime: {
      type: Number,
      default: 0
    }
  },

  created () {
    // 记录上一次的结束时间
    this.lastTime = this.endTime

    // 先执行一次
    this.convertEndTimeToObject()

    // 每秒钟执行一次
    this.timer = setInterval(() => {
      this.convertEndTimeToObject()
    }, 1000)
  },

  destroyed () {
    clearInterval(this.timer)
  },

  methods: {
    /**
     * 将截止时间戳转换成对象
     */
    convertEndTimeToObject () {
      // 如果没有结束时间
      if (!this.lastTime || this.lastTime <= 0) {
        return
      }
      // 小时
      const hour = Math.floor(this.lastTime / 1000 / 60 / 60)
      // 分钟
      const minute = Math.floor((this.lastTime - hour * 60 * 60 * 1000) / 60 / 1000)
      // 秒钟
      const second = Math.floor((this.lastTime - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000)
      // 设置时间
      this.times = {
        h: hour < 10 ? `0${hour}` : hour,
        m: minute < 10 ? `0${minute}` : minute,
        s: second < 10 ? `0${second}` : second
      }
      // 将时间-1
      this.lastTime = this.lastTime - 1000
    }
  }
}
</script>

<style lang="less" scoped>
@import "./../../styles/variable";

.count-down {
  align-items: center;
  display: flex;
  justify-content: center;
  text-align: center;
  .block {
    background: @font-color-golden-dark;
    border-radius: 2px;
    color: @write;
    display: inline-block;
    font-size: 18px;
    width: 40px;
    line-height: 40px;
  }
  .colon {
    display: inline-block;
    font-weight: 700;
    line-height: 40px;
    padding: 0 2px;
  }
}
</style>
